<?php
/* 
 *入库管理
 */
class EnterAction extends TransAction {
    public function _filter(&$map) {
        $key = trim($_REQUEST['keywords']);
        if(!empty($key)) {
            $where['Product.name'] = array('like',"%".$key."%");//产品名称
            //$where['enter_no'] = array('like',"%".$key."%");
            $where['_logic'] = "or";
            $map['_complex'] = $where;
        }

        if( $_REQUEST['supplier_id'] != '' )
          $map['supplier_id'] = $_REQUEST['supplier_id'];

        if( $_REQUEST['enter_no'] != '' )
          $map['enter_no'] = array('like',"%".trim($_REQUEST['enter_no'])."%");
        if( $_REQUEST['buy_no'] != '' )
          $map['buy_no'] = array('like',"%".trim($_REQUEST['buy_no'])."%"); //TODO
        
        $sid = $_REQUEST['supplier_id'];
        if(!empty($sid))
            $map['supplier_id'] = $sid;
        //time 
        $cond_time = array();
        if( $_REQUEST['start_time'] != '' )
          array_push($cond_time, array( 'egt' , strtotime($_REQUEST['start_time']) ) );
          //$cond_time = array( 'egt' , strtotime($_REQUEST['start_time']) );
        if( $_REQUEST['end_time'] != '' )
          array_push($cond_time, array( 'elt' , strtotime($_REQUEST['end_time']) ) );
        if( ($_REQUEST['end_time'] != '' ||  $_REQUEST['start_time'] != '' ) )
        $map['create_time'] = $cond_time;
    }

    public function _before_add(){
        parent::_before_add();
        $this->assign('suppliers',getModelIdName('Supplier','sort'));
        if(!empty($_REQUEST['buy_id'])){
            $buy_details = M('Buy_detail')->where('buy_id='.$_REQUEST['buy_id'].' and finish = 0')->findAll(); //未入库结束的
            if(is_array($buy_details))
                $this->assign('buy_details',$buy_details);
        }
    }
    public function _before_index(){
        parent::_before_index();
        $this->assign('suppliers',getModelField('Supplier','id,name','sort'));
        $this->assign('users',getModelField('User'));
    }
    public function  index() {
        $map = $this->_search ();
        if (method_exists ( $this, '_filter' )) {
            $this->_filter ( $map );
        }
        $model = D ('EnterView');
        if (! empty ( $model )) {
            $this->_list(D('EnterView'), $map, $sortBy = '', $asc = false,true);
        }
      $sum_overview = $model->where($map)->field('sum(number) as sum_number,sum(Enter_detail.total) as sum_total')->find();
      $parameters = str_replace(__URL__.'?', '', __SELF__);
      $this->assign('parameters' ,$parameters);
      $this->assign('sum_overview' ,$sum_overview);
        $this->display ();
        return;
    
    }

    public function export_order($value='')
    {
       //替换查询的函数，可以得map.再导出结果
      //file type: order,order_detail,both
      $export_type = $_REQUEST['etype'];
      $this->_filter ( $map );
      $line = "";
      $data = array();
      switch ($export_type) {
             case 'order':
             if(empty($_REQUEST['keywords']))
                $voList = D('Enter')->where($map)->group('id')->findAll( );
              else
                $voList = D('EnterView')->where($map)->group('enter_id')->findAll( );

               $title ="入库单号,供应商,入库时间,总数量,总金额\n";
                $title = iconv('utf-8', 'GBK', $title);
                if( is_array($voList) )
                foreach ($voList as $key => $value) {
                  $data= array(
                     'wholesale_no' => $value['enter_no'],
                     'supplier_name' => iconv('utf-8','GBK',getModelName($value['supplier_id'],'Supplier') ),
                     'create_time' => toDate($value['create_time']),
                     'sum_number' => $value['sum_number'],
                     'total' => $value['total'],
                     );
                    $line .= build_csv_line($data);
                    unset($data);
                } 
                $filename = "DYW_ruku".date('Ymd_His').'.csv'; //设置文件名 
                
                export_csv($filename,$title.$line);
               break;
            case 'detail':
               $voList = D('EnterView')->where($map)->findAll( );
               $title ="入库单号,供应商,产品,单价,数量,小计\n";
                $title = iconv('utf-8', 'GBK', $title);
                $data = array();
                 if( is_array($voList) )
                foreach ($voList as $key => $value) {
                  $data= array(
                     'sale_no' => $value['enter_no'],
                     'customer_name' => iconv('utf-8', 'GBK',$value['sname']),
                     'pname' => iconv('utf-8', 'GBK',$value['name'] ),
                     'price' => $value['enter_price'],
                     'number' => $value['number'],
                     'total' => $value['dtotal']
                     );
                   $line .= build_csv_line($data);
                    unset($data);
                }
                $filename = "DYW_rukumingxi".date('Ymd_His').'.csv'; //设置文件名 
                export_csv($filename,$title.$line);
               break;

           }     
    }

    public function _before_edit() {
        parent::_before_edit();
        $enter_details = M('Enter_detail')->alias('e')->
                            join(C('DB_PREFIX').'Product p on e.product_id = p.id')->
                            where('enter_id = '.$_GET['id'] )->field('e.*,product_id,p.name,p.tm,p.unit_id')->findAll();
        $this->assign('enter_details',$enter_details); 
    }
 
   public function print_enter(){
    parent::edit('Enter','print');   
    }
 
    //批量导入库--采购
    public function fastadd(){
        $this->assign('users',getModelIdName('User'));
        
        $this->assign('suppliers',getModelIdName('Supplier','sort'));
        $this->assign("warehouses", getModelIdName('Warehouse'));
        $this->display();
    }

    public function delete_buydetail($value='')
    {
        $id = $_REQUEST['buydetail_id'];
        M('Buy_detail')->where('id = ' . $id)->delete();
        $this->success("删除采购详情成功");
    }

    //import enter product detail
    public function import(){
        $sheetData = A('Import')->getExcel();
        $Product = M('Product');
        $product_str = "";
        $i = 1; //count import record
        foreach ($sheetData as $key => $value) {
            if ($key > 1) {//从第二行开始读取
                if(empty($value['A']) && empty ($value['B']) )
                   continue;
               $data = array(
                   'tm' => trim($value['A']),   //条码
                   'name' => trim($value['B']),   //数量
                   'number' => trim($value['C']),   //数量
                   'lot' => trim($value['D']),   //生产批号
                   'exp' => trim($value['E']),   //截止有效期
                   'enter_price' => trim($value['F']),   //进价
               );
               //不使用对象$Product->name 以免继承使用之前的值
                    //优先取条码名，如果条码为空，则取第二列的产品名称
                $pt =  empty($data['tm']) ? $Product->getByName($data['name']) : $Product->getByTm($data['tm']) ;
                if(empty($pt) )
                  $pt = $Product->getByName($data['name']);

                $name = $pt['name']; 
                if (empty($name)) {
                   //异常记录显示出来，人工去重后再进行插入操作
                  $data['name'] = '<font color="red">EXCEL第  '.$key.'  行异常,请删除</font>';
                }else{
                    $data['name'] = $name;
                }
                //json only filter td,not li ,so use li to stand out
            $data['unit'] = getModelName($Product->unit_id, 'Unit');
            $product_str .= "<tr class='tLeft' id='product_td'>";
            $product_str .="<td>" . $pt['tm'] . '</td>';
            $product_str .="<td><input type='hidden' name='product_id[]' value='" . $Product->id. "'/> <p class='span3'>" . $data['name'] . '</p></td>';
            $product_str .="<td>" . printLensOption($Product->id) . '</td>';
            $product_str .="<td><input type='text' class='input-mini' name='enter_price[]' value='" . $data['enter_price'] . "'/></td>";
            $product_str .="<td><input type='text' class='input-mini' name='number[]' class ='small' value='".$data['number']."' /></td>";    //数量
            $product_str .="<td class='span1'>" . $data['unit'] . "</td>";    //单位
            $product_str .="<td class='span1'>" . getStock($Product->id,1) . "</td>";    //库存,暂时默认青云路仓库TODO
            $product_str .="<td><input type='text' class='input-small' name='lot[]' value='".$data['lot']."' /></td>";   //产品批号
            $product_str .="<td><input type='text' class='input-small' name='exp[]' onClick='WdatePicker()' value='".$data['exp']."' /></td>";   //有效期
            
           $product_str .=  " <td class='span1'><img src='".__APP__."/Public/images/publish_x.png' alt='删除' onclick='removerow(this);'/>".$i."</td></tr>";
            $data = NULL;
            $i++;
            }
        }
        echo "{";
        echo                "error: '" . $error . "',\n";
        echo                "msg: '" . urlencode(($product_str)) . "'";
        echo "}";
       
    }
    
}
?>
